package vn.lumi.smarthome.ui.scene;

import java.util.ArrayList;

import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Scene;
import vn.lumi.smarthome.ui.base.EditTextCustom;
import vn.lumi.smarthome.ulti.ChangeFont;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class EditSceneFragment extends AbstractSceneFragment {

	private static final int LOADER_ID = 1;
	private static final String TAG = "EditSceneActivity";
	public static final String EDITSCENEFRAGMENT = "EditSceneFragment";

	public static EditSceneFragment newInstance(int roomId, int floorId,
			int sceneId, String nameScene, int sceneMode, int hour, int minute) {
		EditSceneFragment editSceneFragment = new EditSceneFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floorId);
		bundle.putInt(ROOM_ID, roomId);
		bundle.putInt(EXTRA_SCENE_ID, sceneId);
		bundle.putString(EXTRA_SCENE_NAME, nameScene);
		bundle.putInt(EXTRA_SCENE_MODE, sceneMode);
		bundle.putInt(EXTRA_SCENE_HOUR, hour);
		bundle.putInt(EXTRA_SCENE_MINUTE, minute);
		editSceneFragment.setArguments(bundle);
		return editSceneFragment;
	}

	@Override
	public void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		mFloor_id = getArguments().getInt(FLOOR_ID, -1);
		mRoom_id = getArguments().getInt(ROOM_ID, -1);
		mSceneID = getArguments().getInt(EXTRA_SCENE_ID, -1);
		oldSceneName = getArguments().getString(EXTRA_SCENE_NAME);
		oldSceneMode = getArguments().getInt(EXTRA_SCENE_MODE,
				Scene.SCENE_MODE_NORMAL);
		mOldHour = getArguments().getInt(EXTRA_SCENE_HOUR, 0);
		mOldMinute = getArguments().getInt(EXTRA_SCENE_MINUTE, 0);
		mCurrentHour = mOldHour;
		mCurrentMinute = mOldMinute;
		Log.i(TAG, "onCreate " );
	}

	@Override
	public void onLoaderReset(Loader<Device[]> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = super.onCreateView(inflater, container, savedInstanceState);
		btnBack = (Button) view
				.findViewById(R.id.actionbar_setting_activity_back);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		tvCreatScene.setText(getString(R.string.txt_edit_scene));
		mEdtName.setText(oldSceneName);
		Log.i(TAG, "onCreateView " + oldSceneName );
		return view;
	}

	public void refresh(int roomId, int floorId, int sceneId, String nameScene,
			int sceneMode, int hour, int minute) {
		// TODO Auto-generated method stub
		mFloor_id = floorId;
		mRoom_id = roomId;
		mSceneID = sceneId;
		oldSceneName = nameScene;
		oldSceneMode = sceneMode;
		mOldHour = hour;
		mOldMinute = minute;
		mCurrentHour = mOldHour;
		mCurrentMinute = mOldMinute;
		Log.i(TAG, "refresh" + oldSceneName);
	}

	@Override
	public void startLoadDeviceList(LoaderCallbacks<Device[]> loaderCallback) {
		Bundle bundle = new Bundle();
		bundle.putInt(AbstractSceneFragment.EXTRA_TYPE, TYPE_EDIT);
		// bundle.putInt(AbstractSceneActivity.EXTRA_FLOOR_ID, mFloorID);
		// bundle.putInt(AbstractSceneActivity.EXTRA_ROOM_ID, mRoomID);
		getActivity().getSupportLoaderManager()
				.restartLoader(LOADER_ID, bundle, loaderCallback).forceLoad();
	}

	@Override
	public void saveScene() {
		// TODO Auto-generated method stub
		boolean isNameChanged = (!this.oldSceneName.equals(this.mEdtName
				.getText().toString()));

		// mode changed?
		boolean isModeChanged = false;
		int currentSceneMode = 0;
		if (this.tgbSchedule.isChecked())
			currentSceneMode = Scene.SCENE_MODE_AUTO;
		else
			currentSceneMode = Scene.SCENE_MODE_NORMAL;
		if (this.oldSceneMode == currentSceneMode
				&& this.mOldHour == this.mCurrentHour
				&& this.mOldMinute == this.mCurrentMinute)
			isModeChanged = false;
		else
			isModeChanged = true;
		Log.d("EditScene", "mode changed=" + isModeChanged);

		// separate devices
		boolean isDevicesChanged = false;
		this.mNewDevices = this.mDeviceListAdapter.getDevices();
		ArrayList<Integer> unchangedNormalDevicesID = new ArrayList<Integer>();
		ArrayList<Integer> unchangedNormalDevicesState = new ArrayList<Integer>();
		ArrayList<Integer> unchangedRGBsID = new ArrayList<Integer>();
		ArrayList<Integer> unchangedRGBsState = new ArrayList<Integer>();
		ArrayList<Integer> changedNormalDevicesID = new ArrayList<Integer>();
		ArrayList<Integer> changedNormalDevicesState = new ArrayList<Integer>();
		ArrayList<Integer> changedRGBsID = new ArrayList<Integer>();
		ArrayList<Integer> changedRGBsState = new ArrayList<Integer>();
		ArrayList<Integer> newNormalDevicesID = new ArrayList<Integer>();
		ArrayList<Integer> newNormalDevicesState = new ArrayList<Integer>();
		ArrayList<Integer> newRGBsID = new ArrayList<Integer>();
		ArrayList<Integer> newRGBsState = new ArrayList<Integer>();
		ArrayList<Integer> deletedNormalDevicesID = new ArrayList<Integer>();
		ArrayList<Integer> deletedRGBsID = new ArrayList<Integer>();

		for (int i = 0; i < mNewDevices.length; i++) {
			if (mNewDevices[i].isSelected() == true
					&& mOldDevices[i].isSelected() == true) {
				if (!mNewDevices[i].getDeviceState().equals(
						mOldDevices[i].getDeviceState())) {
					// changed device
					if (mNewDevices[i].getType_id() == Device.DEVICE_TYPE_RGB) {
						changedRGBsID.add(mNewDevices[i].getId());
						changedRGBsState.add(mNewDevices[i].getDeviceState()
								.getRGB());
					} else {
						changedNormalDevicesID.add(mNewDevices[i].getId());
						changedNormalDevicesState.add(mNewDevices[i]
								.getDeviceState().getValue());
					}
				} else {
					// unchanged device
					if (mNewDevices[i].getType_id() == Device.DEVICE_TYPE_RGB) {
						unchangedRGBsID.add(mNewDevices[i].getId());
						unchangedRGBsState.add(mNewDevices[i].getDeviceState()
								.getRGB());
					} else {
						unchangedNormalDevicesID.add(mNewDevices[i].getId());
						unchangedNormalDevicesState.add(mNewDevices[i]
								.getDeviceState().getValue());
					}
				}
			} else if (mNewDevices[i].isSelected() == true
					&& mOldDevices[i].isSelected() == false) {
				// new device
				if (mNewDevices[i].getType_id() == Device.DEVICE_TYPE_RGB) {
					newRGBsID.add(mNewDevices[i].getId());
					newRGBsState.add(mNewDevices[i].getDeviceState().getRGB());
				} else {
					newNormalDevicesID.add(mNewDevices[i].getId());
					newNormalDevicesState.add(mNewDevices[i].getDeviceState()
							.getValue());
				}
			} else if (mNewDevices[i].isSelected() == false
					&& mOldDevices[i].isSelected() == true) {
				// deleted device
				if (mNewDevices[i].getType_id() == Device.DEVICE_TYPE_RGB) {
					deletedRGBsID.add(mNewDevices[i].getId());
				} else {
					deletedNormalDevicesID.add(mNewDevices[i].getId());
				}
			}
		}
		if (changedNormalDevicesID.size() == 0 && changedRGBsID.size() == 0
				&& newNormalDevicesID.size() == 0 && newRGBsID.size() == 0
				&& deletedNormalDevicesID.size() == 0
				&& deletedRGBsID.size() == 0)
			isDevicesChanged = false;
		else
			isDevicesChanged = true;

		Log.d("EditScene", "devices changed=" + isDevicesChanged);
		Log.d("EditScene",
				"changed devices:" + changedNormalDevicesID.toString()
						+ " changed RGBs:" + changedRGBsID.toString()
						+ " new devices:" + newNormalDevicesID.toString()
						+ " new RGBs:" + newRGBsID.toString()
						+ " deleted devices:"
						+ deletedNormalDevicesID.toString() + " deleted RGBs:"
						+ deletedRGBsID.toString());

		// if nothing changed
		if (isNameChanged == false && isDevicesChanged == false
				&& isModeChanged == false)
			finish();

//		// if just name changed
//		if (isNameChanged == true && isDevicesChanged == false
//				&& isModeChanged == false) {
//			ContentValues values = new ContentValues();
//			values.put(TBL_Scene.NAME, this.medtName.getText().toString());
//			String selection = new String(TBL_Scene._ID + "=?");
//			String[] selectionArgs = new String[] { this.mSceneID + "" };
//			getActivity()
//					.getApplication()
//					.getContentResolver()
//					.update(TBL_Scene.CONTENT_URI_SCENE, values, selection,
//							selectionArgs);
//			finish();
//		}

		 if (isNameChanged == true|isDevicesChanged == true || isModeChanged == true) {
			ContentValues values = new ContentValues();
			values.put("Scene name", this.mEdtName.getText().toString());
			values.put("Scene ID", this.mSceneID);
			values.put("Room id", this.mRoom_id);
			values.put("Scene mode", currentSceneMode);
			values.put("Hour", mCurrentHour);
			values.put("Minute", mCurrentMinute);

			values.put(
					"unchangedNormalDevicesID",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(unchangedNormalDevicesID)));
			values.put(
					"unchangedNormalDevicesState",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(unchangedNormalDevicesState)));

			values.put(
					"unchangedRGBsID",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(unchangedRGBsID)));
			values.put(
					"unchangedRGBsState",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(unchangedRGBsState)));

			values.put(
					"changedNormalDevicesID",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(changedNormalDevicesID)));
			values.put(
					"changedNormalDevicesState",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(changedNormalDevicesState)));

			values.put(
					"changedRGBsID",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(changedRGBsID)));
			values.put(
					"changedRGBsState",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(changedRGBsState)));

			values.put(
					"newNormalDevicesID",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(newNormalDevicesID)));
			values.put(
					"newNormalDevicesState",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(newNormalDevicesState)));

			values.put(
					"newRGBsID",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(newRGBsID)));
			values.put(
					"newRGBsState",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(newRGBsState)));

			values.put(
					"deletedNormalDevicesID",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(deletedNormalDevicesID)));
			values.put(
					"deletedRGBsID",
					AbstractSceneFragment
							.convertIntArrayToString(convertArrayListToArray(deletedRGBsID)));

			getActivity()
					.getApplicationContext()
					.getContentResolver()
					.update(TBL_Scene.CONTENT_URI_EDIT_SCENE, values, null,
							null);
			Log.d(TAG, "Sending command to CP");

			// show dialog
			dialog = new ProgressDialog(new ContextThemeWrapper(getActivity(),
					R.style.AlertDialogCustom));
			dialog.setMessage(getString(R.string.txt_saving_scene_in_HC));
			dialog.setCancelable(false);
			dialog.show();
			// Thay doi font chu cua Dialog
			ChangeFont changeFont = new ChangeFont(getActivity());
			TextView textView = (TextView) dialog
					.findViewById(android.R.id.message);
			textView = changeFont.changeFontTextView(textView,
					R.string.txt_saving_scene_in_HC, LumiHome.font, 16,
					Gravity.NO_GRAVITY,
					getResources().getColor(R.color.greenActionbar));

			// set broadcast receiver
			EditSceneReceiver mEditSceneReceiver = new EditSceneReceiver(dialog);
			IntentFilter filter = new IntentFilter();
			filter.addAction(getString(R.string.txt_vn_lumi_smarthome_edit_scene_successful));
			filter.addAction(getString(R.string.txt_vn_lumi_smarthome_edit_scene_failed));
			getActivity().registerReceiver(mEditSceneReceiver, filter);
			Log.d(TAG, "Registered broadcast receiver");
		}
	}

	public int[] convertArrayListToArray(ArrayList<Integer> input) {
		int[] result = new int[input.size()];
		for (int i = 0; i < input.size(); i++) {
			result[i] = input.get(i);
		}
		return result;
	}

	public class EditSceneReceiver extends BroadcastReceiver {

		private ProgressDialog mDialog;

		public EditSceneReceiver(ProgressDialog dialog) {
			mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			mDialog.cancel();
			getActivity().unregisterReceiver(this);
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_vn_lumi_smarthome_edit_scene_successful))) {
				Log.d(TAG, "received success");
				finish();
			} else if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_vn_lumi_smarthome_edit_scene_failed))) {
				Log.d(TAG, "received failed");
				showCustomDialog(R.string.txt_error,
						R.string.txt_error_cannot_connect_HC);
			}
		}

	}

	public void finish() {
		FragmentManager fm = getActivity().getSupportFragmentManager();
		fm.popBackStack();
	}

}
